<template>
  <div class="page-fina-details">
    <div class="search-bar">
      <el-form
        :inline="true"
        class="search-form"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <!-- 交易时间 -->
          <el-form-item :label="$t('finaManage.transactionHour') + ':'">
            <el-select
              v-model="dateValue"
              @change="onSetDateRange(dateValue)"
            >
              <el-option
                v-for="item in dateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <span
              v-if="dateValue === 1 || dateValue === 2"
              class="time-text"
            >{{ startTime }} {{ $t('date.tip') }} {{ endTime }}</span>
            <span v-if="dateValue === 3">
              <el-date-picker
                v-model="dateRangeParam"
                type="daterange"
                unlink-panels
                range-separator="-"
                :start-placeholder="$t('date.start')"
                :end-placeholder="$t('date.end')"
                value-format="x"
                :clearable="false"
              />
            </span>
          </el-form-item>
          <!-- 订单编号 -->
          <el-form-item :label="$t('order.number') + ':'">
            <el-input
              v-model="orderNumber"
              :placeholder="$t('finaManage.pleEntOrderNum')"
            />
          </el-form-item>
          <!-- 按钮 -->
          <el-form-item>
            <div
              class="primary-btn default-btn"
              @click="searchForm"
            >
              {{ $t('order.query') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="operation-bar">
        <div class="default-btn primary-btn">
          <a @click="onExportFrom()">{{ $t('order.exportForm') }}</a>
        </div>
      </div>
      <div class="table-con">
        <el-table
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          :data="tableData"
          style="width: 99%"
        >
          <el-table-column
            prop="transDate"
            :label="$t('finaManage.transactionHour')"
          />
          <el-table-column
            prop="orderId"
            :label="$t('order.number')"
          />
          <el-table-column
            prop="incPayType"
            :label="$t('shop.ioType')"
          />
          <el-table-column
            prop="payType"
            :label="$t('order.paymentMethod')"
          />
          <el-table-column
            prop="transAmount"
            :label="$t('finaManage.amountTrans')"
          />
        </el-table>
      </div>
      <el-pagination
        class="paging"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
  </div>
</template>

<script setup>
import moment from 'moment'
const dateOptions = [
  {
    label: $t('user.lastSevenDay'),
    value: 1
  },
  {
    label: $t('user.lastThirtyDay'),
    value: 2
  },
  {
    label: $t('user.customRange'),
    value: 3
  }
]
let minAmount = null // 交易金额
let maxAmount = null
const isFilter = ref(false) //  筛选按钮判断
const incPayType = ref(0) //  筛选条件
const payType = ref(-1) // 当前选中的支付方式 -1表示不限
watch(isFilter, val => {
  if (!val) {
    incPayType.value = 0
    minAmount = null
    maxAmount = null
    payType.value = -1
  }
})
const storeId = ref(-1) // 门店切换数据
const dateRangeParam = ref([]) // 时间选择器
watch(
  [dateRangeParam, storeId],
  () => {
    searchForm()
  },
  { deep: true }
)
onMounted(() => {
  onGetShopList()
  onSetDateRange(1)
})

// 点击查询
const orderNumber = ref('') // 单号输入
const payTypeList = reactive([
  $t('order.pointsPayment'),
  $t('platform.weChatPay'),
  $t('platform.aliPay'),
  $t('order.wechatScanCodePayment'),
  $t('order.wechatH5Payment'),
  $t('order.weclAccountPay'),
  $t('order.alipayH5Payment'),
  $t('order.alipayAPPPayment'),
  $t('order.wechatAPPPayment'),
  $t('order.balancePayment')
]) // 所有支付方式
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const tableData = ref([
  { transDate: null, orderNumber: null, incPayType: null, payType: null, transAmount: null }
]) //  表格数据
let tempFormData = {}

const searchForm = () => {
  page.value.currentPage = 1
  tempFormData = Object.assign({
    start: dateRangeParam.value[0],
    end: dateRangeParam.value[1],
    stationId: storeId.value,
    orderNumber: orderNumber.value,
    payType: payType.value,
    incPayType: incPayType.value,
    minAmount,
    maxAmount,
    current: page.value.currentPage,
    size: page.value.pageSize
  })
  http({
    url: http.adornUrl('/platform/financialManagement/getFinanDetail'),
    method: 'get',
    params: http.adornParams({
      start: dateRangeParam.value[0],
      end: dateRangeParam.value[1],
      stationId: storeId.value,
      orderNumber: orderNumber.value,
      payType: payType.value,
      incPayType: incPayType.value,
      minAmount,
      maxAmount,
      current: page.value.currentPage,
      size: page.value.pageSize
    })
  }).then(({ data }) => {
    tableData.value = data.records
    // 将支付类型（int）转中文（str）
    tableData.value.forEach(element => {
      element.payType = payTypeList[element.payType]
      if (element.incPayType === '1') {
        element.incPayType = $t('shop.income')
      } else {
        element.incPayType = $t('shop.pay')
      }
    })
    page.value.currentPage = data.current
    page.value.pageSize = data.size
    page.value.total = data.total
  })
}
// 页数查询
const onGetFinaDataByCurrPage = () => {
  http({
    url: http.adornUrl('/platform/financialManagement/getFinanDetail'),
    method: 'get',
    params: http.adornParams({
      start: tempFormData.start,
      end: tempFormData.end,
      stationId: tempFormData.stationId,
      orderNumber: tempFormData.orderNumber,
      payType: tempFormData.payType,
      incPayType: tempFormData.incPayType,
      minAmount: tempFormData.minAmount,
      maxAmount: tempFormData.maxAmount,
      current: tempFormData.current,
      size: tempFormData.size
    })
  }).then(({ data }) => {
    tableData.value = data.records
    // 将支付类型（int）转中文（str）
    tableData.value.forEach(element => {
      element.payType = payTypeList[element.payType]
      if (element.incPayType === '1') {
        element.incPayType = $t('shop.income')
      } else {
        element.incPayType = $t('shop.pay')
      }
    })
    page.value.currentPage = data.current
    page.value.pageSize = data.size
    page.value.total = data.total
  })
}
// 清空
const onResetSearch = () => {
  orderNumber.value = null
  payType.value = -1
  incPayType.value = 0
  maxAmount = null
  minAmount = null
}

const onExportFrom = () => {
  http({
    url: http.adornUrl('/platform/financialManagement/getFinanDetailForm'),
    method: 'get',
    params: http.adornParams({
      start: tempFormData.start,
      end: tempFormData.end,
      stationId: tempFormData.stationId,
      orderNumber: tempFormData.orderNumber,
      payType: tempFormData.payType,
      incPayType: tempFormData.incPayType,
      minAmount: tempFormData.minAmount,
      maxAmount: tempFormData.maxAmount
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    const fileName =
      $t('finaManage.finaDeta') +
      '(' +
      moment(tempFormData.start).format('yyyy-MM-DD') +
      ' ' +
      $t('date.tip') +
      ' ' +
      moment(tempFormData.end).format('yyyy-MM-DD') +
      ').xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) {
      // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}
// 1-3:最近7天、最近30天、自定义时间
const dateRange = ref([]) // 展示的时间参数
const startTime = ref('') // 开始时间
const endTime = ref('') // 结束时间
const dateValue = ref(1) //  时间栏默认选中
const onSetDateRange = val => {
  let startDay = null
  let endDay = null
  dateValue.value = val
  if (val === 1) {
    startDay = -7
    endDay = -1
  } else if (val === 2) {
    startDay = -30
    endDay = -1
  } else if (val === 3) {
    startDay = -2
    endDay = 0
  } else {
    return
  }
  // 开始时间
  const isStartTime = moment().add(startDay, 'days').startOf('days')
  // 结束时间
  const isEndTime = moment().add(endDay, 'days').endOf('days')
  startTime.value = isStartTime.format('L')
  endTime.value = isEndTime.format('L')
  dateRange.value = [startTime.value, endTime.value]
  dateRangeParam.value = [
    moment(startTime.value).unix() * 1000,
    moment(endTime.value).unix() * 1000
  ]
}
// 页数的切换
const onPageSizeChange = val => {
  page.value.pageSize = val
  tempFormData.size = val
  onGetFinaDataByCurrPage()
}
//  换页
const onPageChange = val => {
  page.value.currentPage = val
  tempFormData.current = val
  onGetFinaDataByCurrPage()
}
const dropDowmOptions = [
  {
    label: $t('date.a'),
    value: -1
  }
]
const onGetShopList = () => {
  http({
    url: http.adornUrl('/platform/financialManagement/getStation'),
    method: 'get',
    params: http.adornParams({
      shopId: 1
    })
  }).then(({ data }) => {
    if (data) {
      for (let i = 0; i < data.length; i++) {
        dropDowmOptions.push({
          label: data[i].stationName,
          value: data[i].stationId
        })
      }
      dropDowmOptions.push({
        label: $t('product.other'),
        value: -2
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.page-fina-details {
  .time-text {
    padding-left: 10px;
    color: #999;
  }
  .default-btn {
    a {
      text-decoration: none;
      color: unset;
    }
  }
}
</style>
